/*
package com.xit.hitmouse.ui;

import static java.security.AccessController.getContext;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Objects;
import java.util.Random;
import java.util.Vector;

//import com.example.hitmouse.R;
import com.xit.hitmouse.Bean.MapBean;
import com.xit.hitmouse.Bean.MouseBean;
import com.xit.hitmouse.R;
import com.xit.hitmouse.controller.Controller;
import com.xit.hitmouse.utils.ConvertUtils;

import android.animation.ObjectAnimator;
import android.animation.ValueAnimator;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

public class HitActivity extends Activity{

    private TextView timer;  //显示时间
    private TextView scoreView;  //显示分数
    private RelativeLayout layout;
    private LinearLayout layoutParent;
    private Handler handler;
    private int score = 0;
    private int recLen = 30;
    Controller controller;
    Boolean musicPlay=false;

    private  ValueAnimator animator; //动画效果的

    //多只地鼠
    private Vector<MouseBean> mouses = new Vector<>();


    public int[][] position ; //洞穴位置

    private MapBean mapBean; //地图
    private  int type ; //模式类型  简单、中等还是困难
    private HashSet<Integer> mousePositions = new HashSet<>(); //地鼠位置
    ArrayList<Integer> mouseList;// 老鼠照片 根据不同的难度产生不同的老鼠
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.hit_layout);
        init();
        initMap();
        initMouse();
        new Thread(new MyThread()).start();
    }


    //////////////////////////////
    final Handler timerHandler = new Handler(){
        public void handleMessage(Message msg){
            int index = 0;
            switch (msg.what) {
                case 1:
                    recLen--;
                    timer.setText("" + recLen);
                    if(recLen==0){
                        Intent intent = new Intent(HitActivity.this,GameOver.class);
                        intent.putExtra("score", score+"");
                        startActivity(intent);
                        controller.stop();
                        HitActivity.this.finish();
                    }
                    break;


                default:
            }
            super.handleMessage(msg);
        }
    };

    public class MyThread implements Runnable{
        @Override
        public void run(){
            while(true){
                try{
                    Thread.sleep(1000);
                    Message message = new Message();
                    message.what = 1;
                    timerHandler.sendMessage(message);
                }catch (Exception e) {
                }
            }
        }
    }



    private  void init(){
        timer = (TextView) findViewById(R.id.timer);
        scoreView =(TextView) findViewById(R.id.score);
        layout =  findViewById(R.id.layout);
        layoutParent=findViewById(R.id.layoutParent);
        controller = new Controller(HitActivity.this);
        //当没有打到时候的声音，还在考虑要不要
//        layout.setOnClickListener(new OnClickListener() {
//            @Override
//
//             public void onClick(View v) {
//            controller.playSound(R.raw.laugh);
//
//             }
//
//       });
        //播放背景音乐
        if(!musicPlay){
            controller.play();
            musicPlay=true;
        }
    }

    private  void initMap(){
        Intent intent = getIntent();
        final int diffity = Integer.parseInt(intent.getStringExtra("diffity"));


        type =Integer.parseInt(intent.getStringExtra("maptype"));
        mapBean=new MapBean(type);

        position=mapBean.getPosition();
        //设置背景场景
        layoutParent.setBackgroundResource(mapBean.getBackground());
// 设置地图洞穴
        RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams(
                RelativeLayout.LayoutParams.WRAP_CONTENT, // 宽度设置为自适应
                RelativeLayout.LayoutParams.WRAP_CONTENT  // 高度设置为自适应
        );

        // 9个洞穴
        for (int i = 0; i < 9; i++) {
            final 	ImageView newMap = new ImageView(this);
            newMap.setImageResource(mapBean.getCave());

            // 设置洞穴大小
            layoutParams.width = ConvertUtils.dpConvertPix(this, 100);
            layoutParams.height = ConvertUtils.dpConvertPix(this, 45);
            // 设置洞穴位置
            newMap.setX ( position[i][0] ); // X 轴位置
            newMap.setY ( position[i][1] );  // Y 轴位置
            newMap.setVisibility(View.VISIBLE);
            newMap.setLayoutParams(layoutParams);

            float x = newMap.getX();
            float y = newMap.getY();
            Log.d("MouseCoordinates11", "X: " + x + ", Y: " + y);
            //
            layout.addView(newMap);

        }

    }

    private  void initMouse(){
        //添加老鼠类型  根据地图类型来设置
        mouseList=new ArrayList<>();
        mouseList.add(R.drawable.mouse_1);
        if(type!=1){  //中等难度 这样写可以少写一次add
            mouseList.add(R.drawable.mouse_2);
        }
        if(type==3){
            mouseList.add(R.drawable.mouse_13);
        }

        // 生成多只地鼠
        Runnable mouseGenerator = new Runnable() {
            @Override
            public void run() {
                generateMouse();
                handler.postDelayed(this, 2001); // 间隔两秒生成一批地鼠
                //老鼠的持续显示时间
                handler.post(()-> {
                    Iterator<MouseBean> iterator = mouses.iterator();
                    while (iterator.hasNext()) {
                        MouseBean mousebean = iterator.next();
                        if (!mousebean.isLive()) {  //如果老鼠消失了
                            ImageView mouse = mousebean.getMouses();
                            layout.removeView(mouse);
                            iterator.remove(); // 使用迭代器安全地删除元素
                            mousePositions.remove(mousebean.getMousePositions());//移除老鼠的位置
                        }
                    }
                }); //
            }
        };




        //消息处理器
        handler = new Handler(){
            public  void handleMessage(Message msg) {

                if(msg.what==2){
                    //判断有没有被打死
                    //这里其实可以简化呀，直接用一个临时变量存储上一个点击的老鼠即可
                    for (final MouseBean mousebean : mouses) {
                        ImageView mouse = mousebean.getMouses();
                        if (mousebean.isTouch()) { //判断有没有被打中

                            mouse.setImageResource(R.drawable.hit);
                            mouse.setVisibility(View.VISIBLE);
                            controller.playSound(R.raw.hit_sound);
                            controller.playSound(R.raw.dizzy);

                            handler.postDelayed(new Runnable() { //移除图片
                                @Override
                                public void run() {
                                    layout.removeView(mouse);
                                    mouses.remove(mousebean); // 从集合中删除对应的 老鼠对象
                                    mousePositions.remove(mousebean.getMousePositions());//移除老鼠的位置

                                }
                            }, 500); // 击中效果持续时间500ms

                        }
                    }
                }

                super.handleMessage(msg);
            }

        };
        handler.post(mouseGenerator); // 开始执行生成地鼠的任务

    }


    //生成多只地鼠
    private void generateMouse() {

        // 创建并设置相对布局参数  老鼠的
        RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams(
                RelativeLayout.LayoutParams.WRAP_CONTENT, // 宽度设置为自适应
                RelativeLayout.LayoutParams.WRAP_CONTENT  // 高度设置为自适应
        );
        // 创建并设置相对布局参数  血条的
        RelativeLayout.LayoutParams layoutParams2= new RelativeLayout.LayoutParams(
                RelativeLayout.LayoutParams.WRAP_CONTENT, // 宽度设置为自适应
                RelativeLayout.LayoutParams.WRAP_CONTENT  // 高度设置为自适应
        );
        int count = new Random().nextInt(3)+1; //随机生成1-3的随机数
        // 在一个循环中创建多只老鼠，并添加到集合中
        for (int i = 0; i < count; i++) {
            final 	ImageView newMouse = new ImageView(this);
            final 	ImageView newMouseHp = new ImageView(this); //老鼠的血条
            //随机生成老鼠的类型
            int index2 = new Random().nextInt(mouseList.size()); //随机生成0-2的随机数
//				newMouse.setImageResource(mouseList.get(index2));

//			MouseComponent mouseComponent = new MouseComponent(this);
//			mouseComponent.setMouseImage(R.drawable.mouse_13);
//			mouseComponent.setHealthBarImage(R.drawable.l100);
//			mouseComponent.startTimer(60); // 启动60秒的倒计时
//
//			layout.addView(mouseComponent); // 将组件添加到布局中

            // 设置老鼠大小
            layoutParams.width = ConvertUtils.dpConvertPix(this, 100);
            layoutParams.height = ConvertUtils.dpConvertPix(this, 90);
            // 设置老鼠血条大小
            layoutParams2.width = ConvertUtils.dpConvertPix(this, 100);
            layoutParams2.height = ConvertUtils.dpConvertPix(this, 40);

            // 设置老鼠的位置
            int index = getRandomUniquePosition();//生成一个随机的位置
            newMouse.setX ( position[index][0] ); // X 轴位置
            newMouse.setY ( position[index][1]-150 );  // Y 轴位置

            // 设置老鼠血条的位置
            newMouseHp.setX ( position[index][0] ); // X 轴位置
            newMouseHp.setY ( position[index][1]-110 );  // Y 轴位置
//			newMouseHp.setImageResource(R.drawable.l100);

//			//实现逐渐显示老鼠功能
//			Bitmap fullBitmap = BitmapFactory.decodeResource(getResources(), mouseList.get(index2)); // 加载完整的老鼠图片
//			// 假设初始显示的是腿部，裁剪出腿部的部分（假设腿部占据了图片的下半部分）
//			int legHeight = fullBitmap.getHeight() / 2; // 腿部的高度，这里假设腿部在图片的下半部分
//			Bitmap legBitmap = Bitmap.createBitmap(fullBitmap, 0, 0, fullBitmap.getWidth(), legHeight);
//			// 将裁剪后的腿部图片显示在ImageView中
//			newMouse.setImageBitmap(legBitmap);
//			// 使用属性动画逐步显示完整的老鼠
//			ValueAnimator animator = ValueAnimator.ofInt(legHeight, fullBitmap.getHeight());
//			animator.setDuration(1000); // 动画持续3秒，可根据实际情况调整
//
//			animator.addUpdateListener(animation -> {
//				int value = (int) animation.getAnimatedValue();
//				// 根据动画的进度改变裁剪区域，逐步显示完整的老鼠
//				Bitmap displayedBitmap = Bitmap.createBitmap(fullBitmap, 0, 0, fullBitmap.getWidth(), value);
//				newMouse.setImageBitmap(displayedBitmap);
//			});
//			animator.start();

            animationEffects(mouseList.get(index2),newMouse);
            animationEffects(R.drawable.l100,newMouseHp);




            // 将新创建的老鼠添加到集合中
            MouseBean mouseBean = new MouseBean();
            mouseBean.setMouses(newMouse);
            mouseBean.setMousePositions(index);

            mouseBean.setType(index2+1); //设置不同的老鼠类型

            mouses.add(mouseBean);




            newMouse.setVisibility(View.VISIBLE);
            newMouseHp.setVisibility(View.VISIBLE);
            newMouse.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View v) {
                    animator.cancel(); // 当点击以后就 取消动画
                    Log.d("MouseCoordinates22", "老鼠被打中了");

//				Message m = new Message();
                    Message m=Message.obtain();
                    m.what=2;
                    mouseBean.setTouch(true);

                    mouseBean.reduceHp(); //点击以后减少生命
                    Log.i("mouseHp",mouseBean.getHp()+"");
                    if(mouseBean.isKill()) {  // hp<=0的处理
                        handler.sendMessage(m);
                        score+= mouseBean.getValue();
                        newMouse.setEnabled(false);
                    }




                    scoreView.setText(score+"");
                }
            });
			*/
/*这种无法实现 点击两次老鼠才被击毙，因为点击抬起算两次操作
			newMouse.setOnTouchListener(new View.OnTouchListener() {
*//*

            newMouse.setLayoutParams(layoutParams);
            float x = newMouse.getX();
            float y = newMouse.getY();
            Log.d("MouseCoordinates", "X: " + x + ", Y: " + y);
            // 将老鼠添加到界面上
            layout.addView(newMouse);

            newMouseHp.setLayoutParams(layoutParams2);
            layout.addView(newMouseHp);




        }
    }
    private  void animationEffects(int image , ImageView arg){
        //实现逐渐显示老鼠功能
        Bitmap fullBitmap = BitmapFactory.decodeResource(getResources(),image); // 加载完整的老鼠图片
        // 假设初始显示的是腿部，裁剪出腿部的部分（假设腿部占据了图片的下半部分）
        int legHeight = fullBitmap.getHeight() / 2; // 腿部的高度，这里假设腿部在图片的下半部分
        Bitmap legBitmap = Bitmap.createBitmap(fullBitmap, 0, 0, fullBitmap.getWidth(), legHeight);
        // 将裁剪后的腿部图片显示在ImageView中
        arg.setImageBitmap(legBitmap);
        // 使用属性动画逐步显示完整的老鼠
        animator = ValueAnimator.ofInt(legHeight, fullBitmap.getHeight());
        animator.setDuration(1000); // 动画持续3秒，可根据实际情况调整

        animator.addUpdateListener(animation -> {
            int value = (int) animation.getAnimatedValue();
            // 根据动画的进度改变裁剪区域，逐步显示完整的老鼠

            Bitmap displayedBitmap = Bitmap.createBitmap(fullBitmap, 0, 0, fullBitmap.getWidth(), value);
            arg.setImageBitmap(displayedBitmap);


        });

        if(image == R.drawable.l100){
            Log.i("asd","1");
            //设置血条的滚动效果
            ObjectAnimator translationAnimator = ObjectAnimator.ofFloat(arg, "translationY", arg.getTranslationY(), arg.getTranslationY() - 100f);
            translationAnimator.setDuration(1000); // 设置滚动动画持续1秒
            translationAnimator.start();
        }


        animator.start();
    }
    //生成老鼠的随机位置
    private int getRandomUniquePosition() {
        int index = new Random().nextInt(position.length);
        while (mousePositions.contains(index)) {
            index = new Random().nextInt(position.length);
        }
        mousePositions.add(index);
        return index;
    }

    @Override
    protected void onPause(){
        if(controller.isPlay()){
            controller.pauseMusic();
        }
        super.onPause();

    }
    @Override
    protected void onDestroy() {
        handler.removeCallbacksAndMessages(null); // 移除所有的任务和消息
        if(controller.isPlay()){
            controller.pauseMusic();
        }
        super.onDestroy();

    }
    @Override
    public void onBackPressed() {
        if (controller != null) {
            controller.stop(); // 停止音乐播放
        }
        super.onBackPressed(); // 继续返回操作
    }



}
//*/
